﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;

namespace Nirvana
{
    /// <summary>
    /// 自定义Culling功能脚本
    /// </summary>
    public class CullingManager : Singleton<CullingManager>
    {
        private LinkedList<NirvanaRenderer> nirvanalinkedlist = new LinkedList<NirvanaRenderer>();
        private List<NirvanaRenderer> allRendererList = new List<NirvanaRenderer>();



        public LinkedListNode<NirvanaRenderer> RegisterRenderer(NirvanaRenderer renderer)
        {
            return this.nirvanalinkedlist.AddLast(renderer);
        }
        public void UnregisterRenderer(LinkedListNode<NirvanaRenderer> node)
        {
            this.nirvanalinkedlist.Remove(node);
        }

        public void CullingRenderers(Plane[] planes)
        {
            Assert.AreEqual<int>(0, this.allRendererList.Count);
            LinkedListNode<NirvanaRenderer> linkedListNode = this.nirvanalinkedlist.First;
            while (linkedListNode != null)
            {
                NirvanaRenderer value = linkedListNode.Value;
                linkedListNode = linkedListNode.Next;
                Bounds[] customBounds = value.CustomBounds;
                if (customBounds != null && customBounds.Length > 0)
                {
                    bool flag = false;
                    foreach (Bounds bounds in customBounds)
                    {
                        //检测，此对象在cameras视锥体的六个面有重合
                        if (GeometryUtility.TestPlanesAABB(planes, bounds))
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        value.UnityRenderer.enabled = false;
                        this.allRendererList.Add(value);
                    }
                }

            }

        }

        public void RestoreRenderers()
        {
            for (int i = 0; i < this.allRendererList.Count; i++)
            {
                NirvanaRenderer nirvanaRenderer = this.allRendererList[i];
                nirvanaRenderer.UnityRenderer.enabled = true;
            }
            this.allRendererList.Clear();
        }


    }
}

